import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { saveDraft, addActivity, queryByUpdate } from '../../services/login';
import { Steps, Popover, Form, Button, message } from 'antd';
import { history } from 'umi';
import moment from 'moment';
import BasicActivityForm from './components/BasicActivityForm';
import ActivityInformationForm from './components/ActivityInformationForm';
import {
  CloseOutlined,
  CaretUpOutlined,
  CaretDownOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import './index.less';

export default function createNewEvent(props) {
  // todo 这是步骤条的状态
  const [stepBar, setStepBar] = useState(1);

  // * ------------------------------------------------
  // todo 这是 报名 标签的数据
  const [labelSignUp, setLabelSignUp] = useState(false);
  const labelSignUpAdd = () => {
    setLabelSignUp(!labelSignUp);
  };

  // todo 这是 投票 标签
  const [labelVote, setLabelVote] = useState(false);
  const labelVoteAdd = () => {
    setLabelVote(!labelVote);
  };

  // todo 这是 门票 标签
  const [labelTickets, setLabelTickets] = useState(false);
  const labelTicketsAdd = () => {
    setLabelTickets(!labelTickets);
  };

  // todo 这是 签到 标签
  const [labelSignIn, setLabelSignIn] = useState(false);
  const labelSignInAdd = () => {
    setLabelSignIn(!labelSignIn);
  };

  // todo 这是 抽奖 标签
  const [labelDrawPrize, setLabelDrawPrize] = useState(false);
  const labelDrawPrizeAdd = () => {
    setLabelDrawPrize(!labelDrawPrize);
  };

  // todo 这是第一页表单的数据
  const [scheduleVOS, setScheduleVOS] = useState([]);

  // todo 这是第二页的表单的数据
  const [secondPageForm, setSecondPageForm] = useState([{}, {}, {}, {}, {}]);

  // * ------------------------------------------------
  // todo 这是控制第一页表单的显示隐藏的数据
  const [firstStyleFlag, setFirstStyleFlag] = useState(true);
  // todo 这是控制第一页表单的显示隐藏的数据
  const [secondStyleFlag, setSecondStyleFlag] = useState(false);

  // todo 这是第一页的表单
  const [form] = Form.useForm();
  const [signUpForm] = Form.useForm();
  const [voteForm] = Form.useForm();

  // todo 这是控制 编辑或者保存草稿的 id
  const [newActivityBasicId, setNewActivityBasicId] = useState(
    props.location.state?.activityBasicId ? props.location.state.activityBasicId : '',
  );

  // * ------------------------------------------------
  // todo 步骤条的数据
  const { Step } = Steps;
  const customDot = (dot, { status, index }) => (
    <Popover
      content={
        <span>
          step {index} status: {status}
        </span>
      }
    >
      {dot}
    </Popover>
  );

  // todo 这是 下一步按钮 事件
  const nextStep = () => {
    setFirstStyleFlag(false);
    setSecondStyleFlag(true);
    setStepBar(2);
  };
  // todo 这是 上一步按钮 事件
  const previous = () => {
    setFirstStyleFlag(true);
    setSecondStyleFlag(false);
    setStepBar(1);
  };

  // todo 这是预览按钮事件
  const previewActivity = () => {
    // console.log(form.getFieldValue().users[0].last.format('YYYY-MM-DD HH:mm'));
    // console.log(voteForm.getFieldValue());
    // console.log(voteForm.getFieldValue().votingObject);
    // const voteDraft = voteForm.getFieldValue();
    // console.log(voteDraft['rangePicker'][0].format('YYYY-MM-DD HH:mm'));
    // voteForm.validateFields();
    console.log(form.getFieldValue());
    // console.log(props.location.state.activityBasicId);
    // setActivityBasicId(props.location.state.activityBasicId);
    // console.log(activityBasicId);
    // console.log(signUpForm.getFieldValue());
  };

  // ! 这是保存草稿的按钮事件
  const saveDraftClick = async (switchInter) => {
    // todo 这是保存草稿的接口 try catch
    try {
      // todo 这是第一页的表单验证
      const basicInformationDraftVerify = await form.validateFields();
      const basicInformationDraft = form.getFieldsValue();
      // console.log(basicInformationDraft);

      // todo 这是报名的表单验证
      if (labelSignUp) {
        const signUpDraftVerify = await signUpForm.validateFields();
        const signUpDraft = signUpForm.getFieldValue();
        const numberOfApplicants = parseInt(signUpForm.getFieldValue().activityAddress)
          ? parseInt(signUpForm.getFieldValue().activityAddress)
          : 99999;
        const optionalEntryForms = signUpForm.getFieldValue().addItems;
        const signUpBtn = signUpDraft.signUpBtn;
        const signUpBtnList = [];
        signUpBtn.forEach((item) => {
          if (item.classTrue) {
            signUpBtnList.push({ key: item.name });
          }
        });
        // console.log(signUpBtnList);

        secondPageForm[0] = {
          activityType: '1',
          startDate: signUpDraft['rangePicker'][0].format('YYYY-MM-DD HH:mm'),
          endDate: signUpDraft['rangePicker'][1].format('YYYY-MM-DD HH:mm'),
          numberLimit: numberOfApplicants,
          requiredEntryForms: signUpBtnList,
          optionalEntryForms: optionalEntryForms,
        };
        setSecondPageForm([...secondPageForm]);
      } else {
        secondPageForm[0] = {};
        setSecondPageForm([...secondPageForm]);
      }

      // todo 这是投票的表单验证
      if (labelVote) {
        const voteDraftVerify = await voteForm.validateFields();
        const voteDraft = voteForm.getFieldValue();
        let voteObjectVOSList;
        voteObjectVOSList = voteForm.getFieldValue().votingObject?.map((item) => {
          return {
            pictureKey: item.first2[0].response
              ? item.first2[0].response.data.imgKey
              : item.first2[0].uid,
            pictureUrl: item.first2[0].response
              ? item.first2[0].response.data.imgUrl
              : item.first2[0].url,
            name: item.first,
            instructions: item.last,
          };
        });

        // const voteObjectVOSList = [];
        secondPageForm[1] = {
          activityType: '2',
          startDate: voteDraft['rangePicker'][0].format('YYYY-MM-DD HH:mm'),
          endDate: voteDraft['rangePicker'][1].format('YYYY-MM-DD HH:mm'),
          voteWay: voteDraft.votingMethod,
          voteObjectVOS: voteObjectVOSList,
        };
        setSecondPageForm([...secondPageForm]);
        // console.log(voteDraft['rangePicker'][0].format('YYYY-MM-DD HH:mm'));
      } else {
        secondPageForm[1] = {};
        setSecondPageForm([...secondPageForm]);
      }

      // todo 日程集合
      const usersList = basicInformationDraft.users;
      const newUsersList = [];
      if (usersList && usersList[0] !== undefined) {
        usersList.forEach((item) => {
          newUsersList.push({
            scheduleName: item.first ? item.first : '',
            scheduleDate: item.last ? item.last.format('YYYY-MM-DD HH:mm') : '',
          });
        });
      }
      // console.log(newUsersList);
      scheduleVOS[0] = newUsersList;
      setScheduleVOS([...scheduleVOS]);
      // console.log(basicInformationDraft);
      const a = {
        // todo 这是控制 编辑 或者 保存草稿的接口
        activityBasicId: newActivityBasicId,
        // ! 活动名称
        activityName: basicInformationDraft.activityName,
        // todo 活动内容
        activityContent: basicInformationDraft.activitiesTextField
          ? basicInformationDraft.activitiesTextField
          : '',
        // todo 活动地点
        activitySite: basicInformationDraft.activityAddress
          ? basicInformationDraft.activityAddress
          : '',
        // todo 活动主办方
        activityOrganizers: basicInformationDraft.activitySponsorName
          ? basicInformationDraft.activitySponsorName
          : '',
        // ! 活动开始时间
        startDate: basicInformationDraft['rangePicker'][0].format('YYYY-MM-DD HH:mm'),
        // ! 活动结束时间
        endDate: basicInformationDraft['rangePicker'][1].format('YYYY-MM-DD HH:mm'),
        // ! 活动图片key
        pictureKey: basicInformationDraft.uploadImgLeft.fileList[0].response.data.imgKey,
        // ! 活动图片Url
        pictureUrl: basicInformationDraft.uploadImgLeft.fileList[0].response.data.imgUrl,
        // ! 缩略图key
        thumbnailPictureKey: basicInformationDraft.uploadImgRight.fileList[0].response.data.imgKey,
        // ! 缩略图Url
        thumbnailPictureUrl: basicInformationDraft.uploadImgRight.fileList[0].response.data.imgUrl,
        // ! 省编码
        provinceCode: basicInformationDraft.regionSelection[0],
        // ! 市编码
        cityCode: basicInformationDraft.regionSelection[1],
        // ! 是否有报名活动 1-是0-否
        isSignUp: labelSignUp,
        // ! 是否有抢票活动 1-是0-否
        isRobTickets: labelTickets,
        // ! 是否有签到活动 1-是0-否
        isSignIn: labelSignIn,
        // ! 是否有投票活动 1-是0-否
        isVote: labelVote,
        // ! 是否有抽奖活动 1-是0-否
        isLuckyDraw: labelDrawPrize,
        // todo 日程对象集合
        scheduleVOS: scheduleVOS[0],
        // ! 活动对象集合报名、投票、抢票、签到、抽奖
        activityVOS: secondPageForm,
      };

      // todo 接口
      let saveDraftResult;
      if (switchInter == 'saveDraft') {
        saveDraftResult = await saveDraft(a);
      } else if (switchInter == 'addActivity') {
        saveDraftResult = await addActivity(a);
      }
      if (saveDraftResult.code == 200) {
        if (switchInter == 'saveDraft') {
          if (newActivityBasicId) {
            message.success('修改草稿成功');
            history.push('/');
          } else {
            message.success('保存草稿成功');
            // history.push('/');
          }
        } else if (switchInter == 'addActivity') {
          message.success('创建活动成功');
          history.push('/');
        }
      } else {
        message.error(saveDraftResult.message);
      }
    } catch (error) {
      console.log(error);
      try {
        message.warning(error.errorFields[0].errors[0]);
      } catch {
        console.log(error);
        message.error('保存失败');
      }
    }
  };

  // *----------------------------------------------------
  // todo 这是编辑的数据 加 回填
  const [editList, setEditList] = useState({});
  useEffect(() => {
    if (props.location.query.id) {
      queryByUpdate({ activityBasicId: props.location.state.activityBasicId }).then((res) => {
        try {
          // console.log(res.data);
          setEditList(res.data);
          // todo 报名
          setLabelSignUp(res.data.isSignUp);
          // todo 投票
          setLabelVote(res.data.isVote);
          // todo 门票
          setLabelTickets(res.data.isRobTickets);
          // todo 标签
          setLabelSignIn(res.data.isSignIn);
          // todo 抽奖
          setLabelDrawPrize(res.data.isLuckyDraw);
          // todo 报名表单的回填
          if (res.data.activityVOS[0].activityType == 1) {
            signUpForm.setFieldsValue({
              // todo 这是活动时间
              rangePicker: [
                moment(res.data.activityVOS[0].startDate, 'YYYY-MM-DD HH:mm'),
                moment(res.data.activityVOS[0].endDate, 'YYYY-MM-DD HH:mm'),
              ],
              // todo 这是报名人数
              activityAddress: res.data.activityVOS[0].numberLimit,
              addItems: res.data.activityVOS[0].optionalEntryForms,
            });
          }
          // todo 投票表单的回填
          if (res.data.activityVOS[1].activityType == 2) {
            // console.log(res.data);
            // console.log(res.data.activityVOS[1].voteObjectVOS);
            voteForm.setFieldsValue({
              rangePicker: [
                moment(res.data.activityVOS[1].startDate, 'YYYY-MM-DD HH:mm'),
                moment(res.data.activityVOS[1].endDate, 'YYYY-MM-DD HH:mm'),
              ],
              votingMethod: '1',
              votingObject: res.data.activityVOS[1].voteObjectVOS?.map((item) => {
                return {
                  first: item.name,
                  last: item.instructions,
                  first2: [{ uid: item.pictureKey, url: item.pictureUrl }],
                };
              }),
              votingMethod: res.data.activityVOS[1].voteWay?.toString(),
            });
          }
        } catch (error) {
          // console.log(error);
          message.error('获取编辑信息失败，请重新获取');
        }
      });
    }
  }, []);

  // * --------------------------------------------------------------------------
  // ! 虚拟 DOM
  return (
    <div className="createNewEvent">
      <div className="activityTitle">
        <p>创建活动 /</p> <p>创建活动</p>
      </div>
      <div className="navigationProgress">
        <p className="navigationProgressTitle">创建活动</p>
        <div className="progressBar">
          <Steps current={stepBar} progressDot={customDot}>
            <Step title="基本信息" />
            <Step icon="none" />
            <Step title="活动信息" />
          </Steps>
        </div>
      </div>
      <div className="activityInformationForm">
        {/* 这是第一页的表单 */}
        <div style={{ display: firstStyleFlag ? 'block' : 'none' }}>
          <BasicActivityForm editList={editList} form={form} />
        </div>
        {/* 这是第二页的表单 */}
        {/* 这是多选标签的大盒子 */}
        <div
          className="multipleChoiceLabelBox"
          style={{ display: secondStyleFlag ? 'block' : 'none' }}
        >
          {/* 这是多重选择标签的小盒子 */}
          <div className="multipleChoiceLabelSon">
            <div className="multipleChoiceLabelBoxSon">
              <div className="multipleChoiceLabelTitle">选择你想要的活动</div>
              <div className="multipleChoiceLabelTitleP">（可多选）</div>
            </div>
            {/* 这是多选标签本签 */}
            <div className="multipleChoiceLabelItself">
              {/* 这是报名 */}
              <div
                className={labelSignUp ? 'labelSignUpStyleCancel' : 'labelSignUpStyleAdd'}
                onClick={labelSignUpAdd}
              >
                报 名
                <div
                  style={{ display: labelSignUp ? 'block' : 'none' }}
                  className="multipleChoiceLabelBtn"
                >
                  <CloseOutlined />
                </div>
              </div>
              {/* 这是投票 */}
              <div
                className={labelVote ? 'labelSignUpStyleCancel' : 'labelSignUpStyleAdd'}
                onClick={labelVoteAdd}
              >
                投 票
                <div
                  style={{ display: labelVote ? 'block' : 'none' }}
                  className="multipleChoiceLabelBtn"
                >
                  <CloseOutlined />
                </div>
              </div>
              {/* 这是门票 */}
              <div
                className={labelTickets ? 'labelSignUpStyleCancel' : 'labelSignUpStyleAdd'}
                onClick={labelTicketsAdd}
              >
                门 票
                <div
                  style={{ display: labelTickets ? 'block' : 'none' }}
                  className="multipleChoiceLabelBtn"
                >
                  <CloseOutlined />
                </div>
              </div>
              {/* 这是签到 */}
              <div
                className={labelSignIn ? 'labelSignUpStyleCancel' : 'labelSignUpStyleAdd'}
                onClick={labelSignInAdd}
              >
                签 到
                <div
                  style={{ display: labelSignIn ? 'block' : 'none' }}
                  className="multipleChoiceLabelBtn"
                >
                  <CloseOutlined />
                </div>
              </div>
              {/* 这是抽奖 */}
              <div
                className={labelDrawPrize ? 'labelSignUpStyleCancel' : 'labelSignUpStyleAdd'}
                onClick={labelDrawPrizeAdd}
              >
                抽 奖
                <div
                  style={{ display: labelDrawPrize ? 'block' : 'none' }}
                  className="multipleChoiceLabelBtn"
                >
                  <CloseOutlined />
                </div>
              </div>
            </div>
          </div>
          {/* 这是样式盒子别动 */}
          <div className="styleBorderRadius"></div>
          {/* 这是多选标签的小盒子  结束*/}
        </div>
        {/* 这是多重选择标签的大盒子 结束 */}
        <div style={{ display: secondStyleFlag ? 'block' : 'none' }}>
          <ActivityInformationForm
            signUpForm={signUpForm}
            voteForm={voteForm}
            labelSignUp={labelSignUp}
            labelVote={labelVote}
            labelTickets={labelTickets}
            labelSignIn={labelSignIn}
            labelDrawPrize={labelDrawPrize}
            editList={editList}
          />
        </div>

        {/* 这是第一页的表单按钮 */}
        <div style={{ display: firstStyleFlag ? 'block' : 'none' }}>
          <Button className="firstSubmissionBtn" onClick={nextStep}>
            下一步
          </Button>
        </div>
        {/* 这是第二页的表单按钮 */}
        <div className="secondButton" style={{ display: secondStyleFlag ? 'block' : 'none' }}>
          <Button
            className="secondReleaseBtn"
            onClick={() => {
              saveDraftClick('addActivity');
            }}
          >
            发布
          </Button>
          <Button className="secondSubmissionBtn" onClick={previous}>
            上一步
          </Button>
        </div>
        <div className="fixedButton">
          <Button className="secondPreviewBtn" onClick={previewActivity}>
            预览
          </Button>
          <Button
            className="secondSaveBtn"
            onClick={() => {
              saveDraftClick('saveDraft');
            }}
          >
            保存草稿
          </Button>
        </div>
      </div>
    </div>
  );
}
